/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Description: Hmfs-tools mkfs sit writer
 */

#include "sit_writer.h"

#include <cinttypes>
#include <string>
#include <sys/types.h>

#include "device_manager.h"
#include "hmfs_common.h"
#include "hmfs_io.h"
#include "hmfs_log.h"
#include "mkfs_format.h"
#include "securec.h"

namespace OHOS {
namespace Hmfs {
SitWriter::SitWriter(MkfsFormat &mkfs) : mkfs_(mkfs) {}

int32_t SitWriter::Format()
{
    HmfsData &hmfsData = mkfs_.hmfsData_;
    uint32_t segmentSize = BLOCKS_PER_SEGMENT * HMFS_BLOCK_SIZE;
    auto buf = static_cast<uint8_t *>(calloc(sizeof(uint8_t), segmentSize));
    if (buf == nullptr) {
        HMFS_ERROR("not enough memory for sit segment!");
        return -1;
    }

    uint64_t offset = hmfsData.sitStartBlkId * HMFS_BLOCK_SIZE;
    HMFS_DEBUG("Formating sit segment at offset 0x%" PRIx64 "", offset);
    for (uint32_t i = 0; i < (hmfsData.segmentCountInSIT / HMFS_SIT_COUNT); i++) {
        if (HmfsIo::GetInstance().DevFill(buf, offset, segmentSize)) {
            HMFS_ERROR("failed to write sit segment!");
            free(buf);
            return -1;
        }
        offset += segmentSize;
    }
    free(buf);

    return 0;
}

} // namespace Hmfs
} // namespace OHOS
